<template>
  <div class="scroll-box">
    <slot></slot>
  </div>
</template>

<script>
import { debounce } from '@/utils/utils'

export default {
  name: "scroll-box",
  props: {
    // 是否开启高度监听
    listenHeight: {
      type: Boolean,
      default: false,
    },
    // 顶部触发距离
    topDistance: {
      type: Number,
      default: 0,
    },
    // 是否禁止顶部回调
    topDisabled: {
      type: Boolean,
      default: false
    },
    // 底部触发距离
    bottomDistance: {
      type: Number,
      default: 0,
    },
    // 是否禁止底部回调
    bottomDisabled: {
      type: Boolean,
      default: false
    },
  },
  mounted () {
    if (this.listenHeight) {
      let debounceFunc = debounce(this.scrollCb)
      // 开启监听
      this.$el.addEventListener('scroll', debounceFunc)
    }
  },
  methods: {
    // 滚动的回调
    scrollCb (e) {
      // console.log(e);
      // e.target
      let el = e.target;
      if (!this.topDisabled && el.scrollTop <= this.topDistance) {
        // 触顶
        console.log('触顶');
        this.$emit('touchTop')
      } else if (!this.bottomDisabled && el.scrollHeight - el.scrollTop - el.clientHeight <= this.bottomDistance) {
        console.log('触底');
        this.$emit('touchBottom')
      }
    },


    // api
    // 判断是否离底
    getIsBottom (distance) {
      let el = this.$el
      return el.scrollHeight - el.scrollTop - el.clientHeight <= distance
    },

    // 触底的方法
    scrollToFunc (behavior = 'smooth', top = 99999999) {
      this.$el.scrollTo({
        top,
        behavior,
      })
    },

    // 数据插入数组后保持当前高度
    async keepHeight (callback) {
      // 加载数据前获取高度
      let originHeight = this.$el.scrollHeight
      // console.log(originHeight);
      console.log(this.$el.scrollHeight, '0----------');

      await callback()

      // 数据渲染完成后恢复原来的高度
      this.$nextTick(() => {
        console.log(this.$el.scrollHeight, '1----------');
        this.scrollToFunc('auto', this.$el.scrollHeight - originHeight)
      })
    }
  }
}
</script>

<style scoped>
</style>